var dbConfig = require('../../../util/dbconfig');
var vertoken = require('../../../util/token_vertify.js')
const bodyParser = require("body-parser");
var moment = require('moment');
var salt = require("crypto-js"); //引入数据库密码加密
//函数封装区域---------------------------------------------------------

//随机数函数
function randomNumber(max, min) {
	return Math.floor(Math.random() * (max - min)) + min
}
//处理数据库返回数据左右括号
function delParentheses(parameter, error) {
	return JSON.parse((parameter.substring(1, parameter.length - 1)))
}
//函数封装区域结束---------------------------------------------------------

//功能区--------------------------------------------------------------

//登录验证(ok)
login = async (req, res) => {
	var Id = req.body.userName;
	var Password = salt.MD5(req.body.passWord);
	var sql = `select user_Id from users where user_Id = "${Id}" and user_pw = '${Password}'`;
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.status(500).send({
				text: '服务器错误,login'
			})
		} else {
			if (data.length == 0) {
				res.send({
					text: '登录失败',
					status: 403
				})
			} else {
				var sql = `select IsAdmin value from users where user_Id = "${Id}"`;
				var sqlArr = [];
				var data = (await dbConfig.SySqlConnect(sql, sqlArr))[0].value;
				if (data != 'true') {
					res.send({
						text: '无权限',
						status: 0
					})
				} else {
					vertoken.setToken(Id, Password).then((data) => {
						res.send({
							token: "Bearer " + data,
							text: '登录成功',
							status: 200
						})
					})
				}
			}
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb);
};

register = async (req, res) => {
	var Id = req.body.userName;
	var Password = salt.MD5(req.body.passWord);
	var sql = `select user_Id from users where user_Id = "${Id}"`;
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.status(500).send({
				text: '服务器错误,register'
			})
		} else {
			if (data.length) {
				res.send({
					text: '用户已存在',
					status: 403
				})
			} else {
				var date = moment().format("YYYY-MM-DD HH:mm:ss");
				let sql =
					`insert into users(user_id,user_pw,create_time,IsSuperAdmin,IsAdmin,Introduction,nickname,img_url,sex) value(?,?,?,?,?,?,?,?,?)`;
				let sqlArr = [`${Id}`,`${Password}`,`${date}`,`false`,`false`,'空空如也','暂无昵称','https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3324287611,3832720410&fm=26&gp=0.jpg',`男`];
				let data = await dbConfig.SySqlConnect(sql, sqlArr);
				if (data.affectedRows == 1) {
					res.send({
						"code": 201,
						"text": "注册成功"
					})
				} else {
					 res.send({
						"text":"注册失败",
						"code":-1
					})
				}
			}
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb);
};

module.exports = {
	login,
	register
};
